#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// 通信双方都需知道对方的IP和端口号，才能发送数据
//  客户端在未来一定要知道服务器的IP地址和端口号
//  ./udp_client server-ip server-port
//  ./udp_client 127.0.0.1 8888

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server-ip server-port" << std::endl;
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd=::socket(AF_INET,SOCK_DGRAM,0);//udp方式创建
    if(sockfd<0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(1);
    }
    //client的端口号一般有os自己随机设定
    //client需要bind的自己的IP和端口，但不需要"显示"的bind
    //client在首次向服务器发数据时，os会自动给client bind 它自己的IP和端口

    struct sockaddr_in server;//套接字信息
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);//*注意端口号转化 */
    server.sin_addr.s_addr=inet_addr(serverip.c_str());

    while(1)
    {
        std::string line;
        std::cout << "Please Enter# ";
        std::getline(std::cin, line);
        //发信息
        int n=sendto(sockfd,line.c_str(),line.size(),0,(struct sockaddr*)&server,sizeof(server));
        if(n>0)
        {
            //发送成功后服务端对消息进行拼接，在发送回客户端
            struct sockaddr_in temp;
            socklen_t len=sizeof(temp);
            char buffer[1024];
            int m=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&temp,&len);
            if(m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                std::cout << "recvfrom error" << std::endl;
                break;
            }
        }
        else
        {
            std::cout << "sendto error" << std::endl;
            break;
        }
    }

    ::close(sockfd);
    return 0;
}